#include "guish.hpp"
#include <fcntl.h>
#include <termios.h>

void closeAllExceptStd()
{
	int maxfds = getdtablesize();
	for(int ii=3; ii<maxfds; ii++)
		close(ii);
}

void setCloseOnExec(int fd, bool closeOnExec)
{
	int flags = fcntl(fd, F_GETFD);
	if(closeOnExec) flags |= FD_CLOEXEC;
	else flags &= ~FD_CLOEXEC;
	
	fcntl(fd, F_SETFD, flags);
}

void setFileAsync(int fd, bool async)
{
	int oldFlags;
	oldFlags = fcntl(fd, F_GETFL);
	
	if(async)
		fcntl(fd, F_SETFL, oldFlags|O_NONBLOCK);
	else
		fcntl(fd, F_SETFL, oldFlags&~O_NONBLOCK);
}

#if defined(__CYGWIN__)
// Workaround for Cygwin, which is missing cfmakeraw. Pasted from man page.
void cfmakeraw(struct termios *termios_p)
{
    termios_p->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
    termios_p->c_oflag &= ~OPOST;
    termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
    termios_p->c_cflag &= ~(CSIZE|PARENB);
    termios_p->c_cflag |= CS8;
}
#endif

void makeTermRaw(int fd)
{
	struct termios termFlags;
	if(tcgetattr(fd, &termFlags)==0) {
		cfmakeraw(&termFlags);
		tcsetattr(fd, TCSANOW, &termFlags);
	}
}

